const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { verifyToken } = require('../utils/jwt');

const auth = async (ctx, next) => {
    let token;

    // 检查请求头中是否有token
    if (
        ctx.headers.authorization &&
        ctx.headers.authorization.startsWith('Bearer')
    ) {
        try {
            token = ctx.headers.authorization.split(' ')[1];

            // 验证token
            const decoded = verifyToken(token);

            // 获取用户信息（不包括密码）
            ctx.state.user = await User.findById(decoded.id).select('-password');

            await next();
        } catch (error) {
            ctx.status = 401;
            ctx.body = {
                success: false,
                message: 'Token无效',
            };
            return;
        }
    }

    if (!token) {
        ctx.status = 401;
        ctx.body = {
            success: false,
            message: '未授权访问，请提供token',
        };
        return;
    }
};

module.exports = auth;